package com.zbkj.crmeb.store.service.impl;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.crmeb.core.common.CommonResult;
import com.zbkj.crmeb.enums.OrderStatusEnum;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.service.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.constants.Constants;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.crmeb.core.config.RestTemplateConfig;
import com.zbkj.crmeb.store.dto.ImPushOrderResDTO;
import com.zbkj.crmeb.store.dto.ImPushOrderResDTO.ImPushOrderDTO.ImPushDataListDTO;
import com.zbkj.crmeb.store.response.StoreCartResponse;
import com.zbkj.crmeb.store.response.StoreProductCartProductInfoResponse;

import lombok.extern.slf4j.Slf4j;

/**
* @author Mr.Zhang
* @description StoreOrderServiceImpl 接口实现
* @date 2020-05-28
*/
@Slf4j
@Service
public class ImOrderTaskServiceImpl implements ImOrderTaskService {
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private StoreOrderInfoService storeOrderInfoService;
    @Autowired
    private StoreOrderStatusService storeOrderStatusService;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    private PurchaseGoodsService purchaseGoodsService;

    @Value("${imPush.token}")
    private String imPushToken;
    @Value("${imPush.url.domain}")
    private String imPushDomain;
    @Value("${imPush.url.updateProduct}")
    private String imPushUpdateProduct;
    @Value("${imPush.url.updateStock}")
    private String imPushUpdateStock;
    @Value("${imPush.url.productBatch}")
    private String imPushProductBatch;
    @Value("${imPush.url.productEndBatch}")
    private String imPushProductEndBatch;
    @Value("${imPush.url.fullUpdateProduct}")
    private String imPushFullUpdateProduct;
    @Value("${imPush.url.orderList}")
    private String imPushOrderList;

	@Override
	public void selectOutOrderList() {
    	// 时间周期为三天
    	long now = new Date().getTime();
    	long start = now - (86400000 * 3);
    	// 查询所有订单
    	List<ImPushDataListDTO> imPushDataListDTOs = new ArrayList<>();
    	imPushDataListDTOs = this.selectOutOrderList(now, start, 1, 50, imPushDataListDTOs);
    	
    	// 同步订单到速云(不考虑IM订单取消或者其他情况, 只做单向单次同步)
    	for(ImPushDataListDTO dto : imPushDataListDTOs) {
            // 验证订单是否已存在
            StoreOrder storeOrder = storeOrderService.getByOrderId("OT" + dto.getOrderLineNum());
            if(!ObjectUtils.isEmpty(storeOrder)) {
            	log.info("--------------- 该笔IM外部订单: {} 已存在 ---------------", "OT" + dto.getOrderLineNum());
            	continue;
            }
            syncOutImOrder(dto);
    	}
    		
	}

    /**
     * 功能描述: 查询im订单状态，更新平台订单状态
     * @Param: []
     * @Return: void
     * @Author: wangzh
     * @Date: 2023/4/11 13:42
     */
    @Override
    public void selectOrderStatus() {
        // 待确认子订单
        List<StoreOrderInfo> storeOrderInfos = storeOrderInfoService.list(Wrappers.<StoreOrderInfo>lambdaQuery()
                .eq(StoreOrderInfo::getAutonomous, 0)
                .eq(StoreOrderInfo::getActualSupplierId, 186)
                .eq(StoreOrderInfo::getStatus, OrderStatusEnum.CONFIRM.getCode()));
        if (CollectionUtils.isEmpty(storeOrderInfos)) {
            log.info("--------------- IM待确认订单为0，不更新订单状态  ---------------");
            return;
        }
        List<Integer> storeOrderInfoIds = storeOrderInfos.stream().map(StoreOrderInfo::getId).collect(Collectors.toList());
        Map<Integer, StoreOrderInfo> orderInfoMap = storeOrderInfos.stream().collect(Collectors.toMap(StoreOrderInfo::getId, e -> e));
        List<PurchaseGoods> purchaseGoods = purchaseGoodsService.list(Wrappers.<PurchaseGoods>lambdaQuery()
                .in(PurchaseGoods::getStoreOrderInfoId, storeOrderInfoIds));
        if (CollectionUtils.isEmpty(purchaseGoods)) {
            log.info("--------------- IM推送订单订单为0，不更新订单状态  ---------------");
        }
        purchaseGoods.forEach(purchaseGoods1 -> {
            CommonResult<Object> info = storeOrderService.getSupplierOrderInfoById(purchaseGoods1.getId());
            JSONObject jsonObject = JSON.parseObject((String) info.getData());
            String orderStatus = jsonObject.getString("orderStatus");
            List<String> statusList = Stream.of("已确认", "已发货", "已收货", "已完成").collect(Collectors.toList());
            // 改变状态
            if (statusList.contains(orderStatus)) {
                StoreOrderInfo storeOrderInfo = orderInfoMap.get(purchaseGoods1.getStoreOrderInfoId());
                storeOrderService.confirmChildOrder(purchaseGoods1.getStoreOrderInfoId(), "im接口查询订单已确认", storeOrderInfo.getActualSupplierId(), storeOrderInfo.getActualCost(), storeOrderInfo.getActualCostEur(), storeOrderInfo.getActualStockAreaCode(),null);
            }
        });
    }

    /**
     * 查询订单列表(三天前到今天的数据)
     * @author daigb
     * @date:  2022-05-17 13:52
     */
    public List<ImPushDataListDTO> selectOutOrderList(Long now, Long start, Integer pageNo, Integer pageSize, List<ImPushDataListDTO> imPushDataListDTOs) {
        try {
        	
            RestTemplate restTemplate = new RestTemplateConfig().restTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.add("Auth-Token", imPushToken);
            HttpEntity<String> formEntity = new HttpEntity<>(null, headers);
            ResponseEntity<String> response = restTemplate.exchange(imPushDomain + imPushOrderList + "?endCreated=" + now 
            		+ "&startCreated=" + start + "&pageNo=" + pageNo + "&pageSize=" + pageSize + "&statusList=[Pending,Confirmed,Shipped,Delivered,Finished]"
            		, HttpMethod.GET, formEntity, String.class);

            ObjectMapper mapper = new ObjectMapper();
            ImPushOrderResDTO imPushOrderResDTO = mapper.readValue(response.getBody(), ImPushOrderResDTO.class);
            if (!imPushOrderResDTO.getSuccess()) {
                log.info("--------------- IM商品反向订单列表获取异常: {} ---------------", imPushOrderResDTO.getMessage());
                return imPushDataListDTOs;
            }
            // 保存订单数据
            imPushDataListDTOs.addAll(imPushOrderResDTO.getImPushOrderDTOs().getImPushDataListDTOs());
            if(imPushOrderResDTO.getImPushOrderDTOs().getTotal() > imPushDataListDTOs.size()) {
            	selectOutOrderList(now, start, ++pageNo, pageSize, imPushDataListDTOs);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return imPushDataListDTOs;
    }
    
    /**
     * 创建订单
     * @author daigb
     * @date:  2022-05-17 19:10
     */
    private void syncOutImOrder(ImPushDataListDTO dto) {
        // 创建寻物订单对象
        StoreOrder storeOrder = new StoreOrder();
        storeOrder.setOrderId("OT" + dto.getOrderLineNum());
        storeOrder.setRealName(dto.getShipToAddress().getName());
        storeOrder.setUserPhone(dto.getShipToAddress().getPhone());
        storeOrder.setUserAddress(dto.getShipToAddress().getAddr());
        storeOrder.setTotalNum(dto.getStock());
        storeOrder.setTotalPrice(dto.getOriginalSupplyPrice());
        storeOrder.setPayPrice(dto.getOriginalSupplyPrice());
        storeOrder.setPayTime(new Date(dto.getCreatedAt()));
        storeOrder.setCreateTime(new Date(dto.getCreatedAt()));
        storeOrder.setCreateName("IM外部订单");
        storeOrder.setProvince(dto.getShipToAddress().getProvince());
        storeOrder.setCity(dto.getShipToAddress().getCity());
        storeOrder.setDistrict(dto.getShipToAddress().getArea());
        storeOrder.setDetail(dto.getShipToAddress().getAddr());
        // 暂时放在寻物
        storeOrder.setMerId(22);
        // 第三方支付订单
        storeOrder.setPayType("other");
        // 默认绑定一个寻物用户
        storeOrder.setUid(293);
        storeOrder.setIsChannel(1);
        // 订单来源 1 寻物 2第三方
        storeOrder.setSource(2);
        // 支付成功
        storeOrder.setPaid(true);
        storeOrder.setStatus(Constants.ORDER_STATUS_H5_CONFIRM);
        storeOrder.setUnique(DigestUtils.md5Hex(dto.getOrderLineNum()));
        // 默认国内订单
        storeOrder.setAreaType(1);
        storeOrderService.save(storeOrder);

        // 创建订单详情
        List<StoreOrderInfo> storeOrderInfos = new ArrayList<>();
        BigDecimal payPrice = BigDecimal.ZERO;
        boolean flag = true;
        // 校验商品
        StoreProductAttrValue storeProductAttrValue = storeProductAttrValueService.getOne(Wrappers.<StoreProductAttrValue>lambdaQuery()
                .eq(StoreProductAttrValue :: getSourceSkuId, dto.getBarcode())
                .last("LIMIT 1")
        );
        if(null == storeProductAttrValue) {
        	log.info("--------------- 订单: {} 该商品: {} sku不存在 ---------------", dto.getOrderLineNum(), dto.getBarcode());
        	return;
        }
        if(dto.getStock() > storeProductAttrValue.getStock()) {
        	log.info("--------------- 订单: {} 该商品: {} 库存不足 ---------------", dto.getOrderLineNum(), dto.getBarcode());
        	return;
        }
        StoreProduct storeProduct = storeProductService.getById(storeProductAttrValue.getProductId());
        
        StoreCartResponse response = new StoreCartResponse();
        response.setCartNum(storeProductAttrValue.getStock());
        response.setCostPrice(storeProductAttrValue.getCost());
        response.setProductId(storeProductAttrValue.getProductId());
        response.setTruePrice(dto.getOriginalSupplyPrice());
        StoreProductCartProductInfoResponse productInfo = new StoreProductCartProductInfoResponse();
        productInfo.setId(storeProduct.getId());
        productInfo.setOtPrice(storeProduct.getOtPrice());
        productInfo.setPrice(storeProduct.getPrice());
        productInfo.setStoreName(storeProduct.getStoreName());
        productInfo.setBarCode(storeProduct.getBarCode());
        productInfo.setTempId(storeProductAttrValue.getTempId());
        productInfo.setKeyword(storeProduct.getKeyword());
        productInfo.setImage(storeProduct.getImage());
        productInfo.setIsEurope(storeProduct.getIsEurope());
        productInfo.setPlatRatio(BigDecimal.ZERO);
        productInfo.setCateId(storeProduct.getCateId());
        productInfo.setBrandName(storeProduct.getBrandName());
        StoreProductAttrValue attrInfo = new StoreProductAttrValue();
        attrInfo.setFirstPrice(BigDecimal.ZERO);
        attrInfo.setSecondPrice(BigDecimal.ZERO);
        attrInfo.setTaxPrice(BigDecimal.ZERO);
        attrInfo.setTaxAndSecondPrice(BigDecimal.ZERO);
        attrInfo.setSuk(storeProductAttrValue.getSuk());
        attrInfo.setBarCode(storeProductAttrValue.getBarCode());
        attrInfo.setPrice(storeProductAttrValue.getPrice());
        attrInfo.setSourceSkuId(storeProductAttrValue.getSourceSkuId());
        attrInfo.setCost(storeProductAttrValue.getCost());
        attrInfo.setSourceCost(storeProductAttrValue.getSourceCost());
        attrInfo.setOtPrice(storeProductAttrValue.getOtPrice());
        attrInfo.setProductPaidPrice(storeProductAttrValue.getPrice());
        attrInfo.setPaidPrice(storeProductAttrValue.getPrice());
        attrInfo.setSubTotalPrice(attrInfo.getPaidPrice());
        attrInfo.setDeductionPrice(BigDecimal.ZERO);
        attrInfo.setUseIntegral(BigDecimal.ZERO);
        attrInfo.setAttrValue(storeProductAttrValue.getAttrValue());
        attrInfo.setImage(storeProductAttrValue.getImage());
        attrInfo.setProductId(storeProduct.getId());
        productInfo.setAttrInfo(attrInfo);
        response.setProductInfo(productInfo);
        StoreOrderInfo storeOrderInfo = new StoreOrderInfo();
        storeOrderInfo.setOrderId(storeOrder.getId());
        storeOrderInfo.setProductId(storeProduct.getId());
        storeOrderInfo.setInfo(JSON.toJSON(response).toString());
        storeOrderInfo.setIsEurope(storeProduct.getIsEurope());
        storeOrderInfo.setUnique(storeProductAttrValue.getSourceSkuId());
        storeOrderInfo.setSuppliersId(storeProduct.getSuppliersId());
        storeOrderInfo.setStatus(Constants.ORDER_STATUS_H5_CONFIRM);
        storeOrderInfo.setRefundStatus(0);
        storeOrderInfo.setPayPrice(attrInfo.getPaidPrice());
        storeOrderInfo.setOrderInfoId("OT" + dto.getOrderLineNum());
        storeOrderInfo.setExchangeRate(storeProduct.getExchangeRate());
        //推送地址
        storeOrderInfo.setDeliveryAddress(dto.getShipToAddress().getAddr());
        storeOrderInfos.add(storeOrderInfo);
        // 保存订单详情
        boolean saveBatchOrderInfosResult = storeOrderInfoService.saveBatch(storeOrderInfos);
        List<StoreOrderInfo> orderInfoList = storeOrderInfoService.list(Wrappers.lambdaQuery(StoreOrderInfo.class).eq(StoreOrderInfo::getOrderId, storeOrder.getId()));
        orderInfoList.forEach(e -> e.setChildOrderNumber(Long.toString(Long.parseLong(storeOrder.getId() + "" + e.getId()), 36).toUpperCase()));
        storeOrderInfoService.saveOrUpdateBatch(orderInfoList);
        if (!saveBatchOrderInfosResult) {
        	log.info("--------------- 订单: {} 该商品: {} 订单生成失败 ---------------", dto.getOrderLineNum(), dto.getBarcode());
        	return;
        }
        // 订单log记录增加
        String message = "同步外部订单";
        storeOrderStatusService.createLog(storeOrder.getId(),storeOrder.getOrderId(), Constants.ORDER_LOG_OTHER_ORDER, message);
    }
    
}
